import { AnimationClip, Sprite, SpriteFrame, UITransform, animation } from 'cc'
import ResourceManage from '../Runtime/resourceManage'
import { StateMachine } from './StateMachine'
import { FSM_PARAMS_TYPE_ENUM } from '../Enums'
import { sortSpriteFrame } from '../Utils'

const ANIMATION_SPEED = 1 / 8

// 2.需要播放动画的能力 animationComponent
export default class State {
  private animationClip: AnimationClip

  constructor(
    private fsm: StateMachine,
    private path: string,
    private wrapMode: AnimationClip.WrapMode = AnimationClip.WrapMode.Normal,
  ) {
    this.init()
  }

  async init() {
    // 加载动画资源
    const promise = ResourceManage.Instance.loadDir(this.path)
    // 因为不同动画加载资源是异步的，所以放到 waitinglist里，通过promise.all 来执行
    this.fsm.waitingList.push(promise)
    // 等待异步执行的结果
    const spriteFrames = await promise

    // 创建对应的动画
    this.animationClip = new AnimationClip()
    const track = new animation.ObjectTrack() // 创建一个对象轨道
    track.path = new animation.TrackPath().toComponent(Sprite).toProperty('spriteFrame')
    const frames: Array<[number, SpriteFrame]> = sortSpriteFrame(spriteFrames).map((item, index) => {
      return [ANIMATION_SPEED * index, item]
    })
    track.channel.curve.assignSorted(frames)
    // 最后将轨道添加到动画剪辑以应用
    this.animationClip.addTrack(track)
    this.animationClip.name = this.path // 动画剪辑的名称

    this.animationClip.duration = frames.length * ANIMATION_SPEED // 整个动画剪辑的周期
    this.animationClip.wrapMode = this.wrapMode // 循环播放
  }

  run() {
    // 避免重复执行
    if (this.fsm.animationComponent?.defaultClip?.name === this.animationClip.name) {
      return
    }
    // 执行动画
    this.fsm.animationComponent.defaultClip = this.animationClip
    this.fsm.animationComponent.play()
  }
}
